package boundary;

import boundary.display.DBarcodeBrowsing;
import components.TabPanel;
import components.utils.ComponentFactory;
import components.utils.observer.TreeUpdater;
import control.Application;
import entity.Entity;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author Juan
 */
public class FMain extends javax.swing.JFrame {
    
    private DBarcodeBrowsing dBarcodeBrowsing = new DBarcodeBrowsing(this, false);
    private Point popupMenuLocation = new Point(0, 0);
    private TreeUpdater clientsUpdater;
    private TreeUpdater serviceRequestsUpdater;

    public FMain() {
        initComponents();
        setLocationRelativeTo(null);
        SPMainPanelScrollPane.getVerticalScrollBar().setUnitIncrement(30);
        SPMainPanelScrollPane.getHorizontalScrollBar().setUnitIncrement(30);
        
        clientsUpdater =
                new TreeUpdater(Application.CLIENT_MANAGER.getCollection(), TMainTree, 0);
        Application.CLIENT_MANAGER.addObserver(clientsUpdater);
        
        serviceRequestsUpdater =
                new TreeUpdater(Application.SERVICE_REQUEST_MANAGER.getCollection(), TMainTree, 1);
        Application.SERVICE_REQUEST_MANAGER.addObserver(serviceRequestsUpdater);
    }
    
    public void initilizeAdmin() {
        RegisterMenu.setVisible(false);
        AdministerMenu.setVisible(true);
    }
    
    public void initializeSecretary() {
       RegisterMenu.setVisible(true);
        AdministerMenu.setVisible(false);
    }
    
    public void openPersonRegistrationPanel() {
        ComponentFactory.addNewSingletonPanel(TPMainPanel,
                ComponentFactory.PERSON_REGISTRATION);
    }
    
    public void openEnterpriseRegistrationPanel() {
        ComponentFactory.addNewSingletonPanel(TPMainPanel,
                ComponentFactory.ENTERPRISE_REGISTRATION);
    }
    
    public void openServiceRequestRegistrationPanel() {
        ComponentFactory.addNewSingletonPanel(TPMainPanel,
                ComponentFactory.SERVICE_REQUEST_REGISTRATION);
    }
    
    public void openEmployeeManagementPanel() {
        ComponentFactory.addNewSingletonPanel(TPMainPanel,
                ComponentFactory.EMPLOYEE_MANAGEMENT);
    }
    
    public void openEmployeeRegistrationPanel() {
        ComponentFactory.addNewSingletonPanel(TPMainPanel,
                ComponentFactory.EMPLOYEE_REGISTRATION);
    }
    
    public void openTestManagementPanel() {
        ComponentFactory.addNewSingletonPanel(TPMainPanel,
                ComponentFactory.TEST_MANAGEMENT);
    }
    
    public void openTestRegistrationPanel() {
        ComponentFactory.addNewSingletonPanel(TPMainPanel,
                ComponentFactory.TEST_REGISTRATION);
    }
    
    public void displayEntity(Entity entity) {
        ComponentFactory.addDisplayPanel(TPMainPanel, entity);
    }
    
    private void showTabbedPanePopup(MouseEvent evt) {
        int indexAtLocation = TPMainPanel.indexAtLocation(evt.getX(), evt.getY());
        if (indexAtLocation > -1) {
            popupMenuLocation = new Point(evt.getPoint());
            PMTabbedPanePopupMenu.show(TPMainPanel, evt.getX(), evt.getY());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PMTabbedPanePopupMenu = new javax.swing.JPopupMenu();
        MICloseTab = new javax.swing.JMenuItem();
        MICloseOther = new javax.swing.JMenuItem();
        MICloseAll = new javax.swing.JMenuItem();
        SPMainSlpitPane = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        TMainTree = new javax.swing.JTree();
        SPMainPanelScrollPane = new javax.swing.JScrollPane();
        TPMainPanel = new javax.swing.JTabbedPane();
        jInternalFrame1 = new javax.swing.JInternalFrame();
        jLabel1 = new javax.swing.JLabel();
        MenuBar = new javax.swing.JMenuBar();
        AdministerMenu = new javax.swing.JMenu();
        MIManageEmployees = new javax.swing.JMenuItem();
        MIManageTests = new javax.swing.JMenuItem();
        RegisterMenu = new javax.swing.JMenu();
        MINew = new javax.swing.JMenuItem();
        MIEnterprise = new javax.swing.JMenuItem();
        MIServiceRequest = new javax.swing.JMenuItem();
        BrowseMenu = new javax.swing.JMenu();
        MIBarcode = new javax.swing.JMenuItem();
        EditMenu = new javax.swing.JMenu();
        MIPreferences = new javax.swing.JMenuItem();
        SessionMenu = new javax.swing.JMenu();
        MILogout = new javax.swing.JMenuItem();
        HelpMenu = new javax.swing.JMenu();
        MIAbout = new javax.swing.JMenuItem();

        MICloseTab.setText("Cerrar Pestaña");
        MICloseTab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MICloseTabActionPerformed(evt);
            }
        });
        PMTabbedPanePopupMenu.add(MICloseTab);

        MICloseOther.setText("Cerrar otras");
        MICloseOther.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MICloseOtherActionPerformed(evt);
            }
        });
        PMTabbedPanePopupMenu.add(MICloseOther);

        MICloseAll.setText("Cerrar todas");
        MICloseAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MICloseAllActionPerformed(evt);
            }
        });
        PMTabbedPanePopupMenu.add(MICloseAll);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Sistema de Información Alpha1");
        setMinimumSize(new java.awt.Dimension(600, 318));

        SPMainSlpitPane.setDividerLocation(150);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Alpha1");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Clientes");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Solicitudes");
        treeNode1.add(treeNode2);
        TMainTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        TMainTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                TMainTreeMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(TMainTree);

        SPMainSlpitPane.setLeftComponent(jScrollPane1);

        SPMainPanelScrollPane.setBorder(null);

        TPMainPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                TPMainPanelMouseReleased(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                TPMainPanelMousePressed(evt);
            }
        });
        SPMainPanelScrollPane.setViewportView(TPMainPanel);

        SPMainSlpitPane.setRightComponent(SPMainPanelScrollPane);

        jInternalFrame1.setVisible(true);

        jLabel1.setText("jLabel1");

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 170, Short.MAX_VALUE)
            .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
                    .addContainerGap(44, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 106, Short.MAX_VALUE)
            .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        AdministerMenu.setText("Administrar");

        MIManageEmployees.setText("Empleados");
        MIManageEmployees.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIManageEmployeesActionPerformed(evt);
            }
        });
        AdministerMenu.add(MIManageEmployees);

        MIManageTests.setText("Análisis");
        MIManageTests.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIManageTestsActionPerformed(evt);
            }
        });
        AdministerMenu.add(MIManageTests);

        MenuBar.add(AdministerMenu);

        RegisterMenu.setText("Registrar");

        MINew.setText("Persona");
        MINew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MINewActionPerformed(evt);
            }
        });
        RegisterMenu.add(MINew);

        MIEnterprise.setText("Empresa");
        MIEnterprise.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIEnterpriseActionPerformed(evt);
            }
        });
        RegisterMenu.add(MIEnterprise);

        MIServiceRequest.setText("Solicitud");
        MIServiceRequest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIServiceRequestActionPerformed(evt);
            }
        });
        RegisterMenu.add(MIServiceRequest);

        MenuBar.add(RegisterMenu);

        BrowseMenu.setText("Consultar");

        MIBarcode.setText("Código de Barras");
        MIBarcode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIBarcodeActionPerformed(evt);
            }
        });
        BrowseMenu.add(MIBarcode);

        MenuBar.add(BrowseMenu);

        EditMenu.setText("Editar");

        MIPreferences.setText("Preferencias");
        EditMenu.add(MIPreferences);

        MenuBar.add(EditMenu);

        SessionMenu.setText("Sesión");

        MILogout.setText("Cerrar Sesión");
        MILogout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MILogoutActionPerformed(evt);
            }
        });
        SessionMenu.add(MILogout);

        MenuBar.add(SessionMenu);

        HelpMenu.setText("Ayuda");

        MIAbout.setText("Acerca de");
        MIAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                MIAboutActionPerformed(evt);
            }
        });
        HelpMenu.add(MIAbout);

        MenuBar.add(HelpMenu);

        setJMenuBar(MenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(SPMainSlpitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(247, Short.MAX_VALUE)
                    .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(132, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(SPMainSlpitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(91, Short.MAX_VALUE)
                    .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(91, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void MINewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MINewActionPerformed
        openPersonRegistrationPanel();
    }//GEN-LAST:event_MINewActionPerformed

    private void MIEnterpriseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIEnterpriseActionPerformed
        openEnterpriseRegistrationPanel();
    }//GEN-LAST:event_MIEnterpriseActionPerformed

    private void MIServiceRequestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIServiceRequestActionPerformed
        openServiceRequestRegistrationPanel();
    }//GEN-LAST:event_MIServiceRequestActionPerformed

    private void TMainTreeMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TMainTreeMousePressed
        TreePath selectedPath = TMainTree.getPathForLocation(evt.getX(), evt.getY());
        
        if (selectedPath != null) {
            if (evt.getClickCount() == 2) {
                DefaultMutableTreeNode lastPathComponent = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
                Object userObject = lastPathComponent.getUserObject();
                displayEntity((Entity) userObject);
            }
        }
    }//GEN-LAST:event_TMainTreeMousePressed

    private void TPMainPanelMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TPMainPanelMouseReleased
        if (evt.isPopupTrigger()) {
            showTabbedPanePopup(evt);
        }
    }//GEN-LAST:event_TPMainPanelMouseReleased

    private void TPMainPanelMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TPMainPanelMousePressed
        if (evt.isPopupTrigger()) {
            showTabbedPanePopup(evt);
        }
    }//GEN-LAST:event_TPMainPanelMousePressed

    private void MICloseTabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MICloseTabActionPerformed
        int indexAtLocation = TPMainPanel.indexAtLocation(popupMenuLocation.x, popupMenuLocation.y);
        TabPanel closingPanel = (TabPanel) TPMainPanel.getComponentAt(indexAtLocation);
        closingPanel.getButtonTabComponent().closeTab();
    }//GEN-LAST:event_MICloseTabActionPerformed

    private void MICloseOtherActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MICloseOtherActionPerformed
        int indexAtLocation = TPMainPanel.indexAtLocation(popupMenuLocation.x, popupMenuLocation.y);
        TabPanel selectedPanel = (TabPanel) TPMainPanel.getComponentAt(indexAtLocation);
        String title = TPMainPanel.getTitleAt(indexAtLocation);
        TPMainPanel.removeAll();
        TPMainPanel.add(selectedPanel, title);
        TPMainPanel.setTabComponentAt(0, selectedPanel.getButtonTabComponent());
    }//GEN-LAST:event_MICloseOtherActionPerformed

    private void MICloseAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MICloseAllActionPerformed
        TPMainPanel.removeAll();
    }//GEN-LAST:event_MICloseAllActionPerformed

    private void MIAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIAboutActionPerformed
        
    }//GEN-LAST:event_MIAboutActionPerformed

    private void MIManageEmployeesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIManageEmployeesActionPerformed
        openEmployeeManagementPanel();
    }//GEN-LAST:event_MIManageEmployeesActionPerformed

    private void MIManageTestsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIManageTestsActionPerformed
        openTestManagementPanel();
    }//GEN-LAST:event_MIManageTestsActionPerformed

    private void MILogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MILogoutActionPerformed
        setVisible(false);
        TPMainPanel.removeAll();
        new FLogin().setVisible(true);
    }//GEN-LAST:event_MILogoutActionPerformed

    private void MIBarcodeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MIBarcodeActionPerformed
        if (dBarcodeBrowsing.isVisible()) {
            dBarcodeBrowsing.requestFocus();
        } else {
            dBarcodeBrowsing.setVisible(true);
        }
    }//GEN-LAST:event_MIBarcodeActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FMain().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu AdministerMenu;
    private javax.swing.JMenu BrowseMenu;
    private javax.swing.JMenu EditMenu;
    private javax.swing.JMenu HelpMenu;
    private javax.swing.JMenuItem MIAbout;
    private javax.swing.JMenuItem MIBarcode;
    private javax.swing.JMenuItem MICloseAll;
    private javax.swing.JMenuItem MICloseOther;
    private javax.swing.JMenuItem MICloseTab;
    private javax.swing.JMenuItem MIEnterprise;
    private javax.swing.JMenuItem MILogout;
    private javax.swing.JMenuItem MIManageEmployees;
    private javax.swing.JMenuItem MIManageTests;
    private javax.swing.JMenuItem MINew;
    private javax.swing.JMenuItem MIPreferences;
    private javax.swing.JMenuItem MIServiceRequest;
    private javax.swing.JMenuBar MenuBar;
    private javax.swing.JPopupMenu PMTabbedPanePopupMenu;
    private javax.swing.JMenu RegisterMenu;
    private javax.swing.JScrollPane SPMainPanelScrollPane;
    private javax.swing.JSplitPane SPMainSlpitPane;
    private javax.swing.JMenu SessionMenu;
    private javax.swing.JTree TMainTree;
    private javax.swing.JTabbedPane TPMainPanel;
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
